<template>
  <div class="customer-review-list">
    <div class="header">
      <h3>客户信息审核</h3>
    </div>

    <div class="filter">
      <el-form :model="filterForm" inline>
        <el-form-item label="审核状态">
          <el-select v-model="filterForm.status" placeholder="请选择" clearable>
            <el-option label="待审核" :value="1" />
            <el-option label="审核通过" :value="2" />
            <el-option label="审核驳回" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" v-loading="loading">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="customer_name" label="客户名称" min-width="150" />
      <el-table-column prop="review_type" label="审核类型" width="100">
        <template #default="{ row }">
          <el-tag :type="row.review_type === 1 ? 'success' : 'warning'">
            {{ row.review_type === 1 ? '新增' : '编辑' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="user_name" label="申请人" width="100" />
      <el-table-column prop="status" label="审核状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="提交时间" width="160" />
      <el-table-column prop="review_time" label="审核时间" width="160" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="text" @click="handleDetail(row)">查看详情</el-button>
          <el-button v-if="row.status === 1" type="text" @click="handleApprove(row, 2)">
            通过
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="text"
            style="color: #f56c6c"
            @click="handleApprove(row, 3)"
          >
            驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 审核详情对话框 -->
    <el-dialog v-model="detailVisible" title="审核详情" width="800px">
      <div v-if="currentReview">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审核类型">
            {{ currentReview.review_type === 1 ? '新增客户' : '编辑客户' }}
          </el-descriptions-item>
          <el-descriptions-item label="申请人">
            {{ currentReview.user_name }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ currentReview.create_time }}
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusType(currentReview.status)">
              {{ getStatusText(currentReview.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div class="data-compare" style="margin-top: 20px">
          <h4>变更内容对比</h4>
          <el-row :gutter="20">
            <el-col :span="12" v-if="currentReview.review_type === 2">
              <div class="compare-card">
                <h5>原始数据</h5>
                <pre>{{ formatJson(currentReview.original_data) }}</pre>
              </div>
            </el-col>
            <el-col :span="currentReview.review_type === 2 ? 12 : 24">
              <div class="compare-card">
                <h5>{{ currentReview.review_type === 1 ? '新增数据' : '修改后数据' }}</h5>
                <pre>{{ formatJson(currentReview.new_data) }}</pre>
              </div>
            </el-col>
          </el-row>
        </div>

        <div v-if="currentReview.review_remark" style="margin-top: 20px">
          <h4>审核备注</h4>
          <p>{{ currentReview.review_remark }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="approveVisible"
      :title="approveStatus === 2 ? '审核通过' : '审核驳回'"
      width="500px"
    >
      <el-form :model="approveForm" label-width="80px">
        <el-form-item label="审核备注">
          <el-input
            v-model="approveForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入审核备注"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="approveVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmApprove" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import request from '@/utils/request'

  const loading = ref(false)
  const submitting = ref(false)
  const tableData = ref<any[]>([])
  const detailVisible = ref(false)
  const approveVisible = ref(false)
  const currentReview = ref<any>(null)
  const approveStatus = ref(2)

  const filterForm = reactive({
    status: '',
  })

  const pagination = reactive({
    current: 1,
    size: 20,
    total: 0,
  })

  const approveForm = reactive({
    remark: '',
  })

  // 获取审核列表
  const getReviewList = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.current,
        limit: pagination.size,
        status: filterForm.status,
      }
      const res = await request({
        url: '/api/crm/customer/reviewList',
        method: 'get',
        params,
      })

      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
    } catch (error) {
      console.error('获取审核列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取状态类型
  const getStatusType = (status: number) => {
    const types: Record<number, string> = {
      1: 'warning',
      2: 'success',
      3: 'danger',
    }
    return types[status] || 'info'
  }

  // 获取状态文本
  const getStatusText = (status: number) => {
    const texts: Record<number, string> = {
      1: '待审核',
      2: '审核通过',
      3: '审核驳回',
    }
    return texts[status] || '未知'
  }

  // 格式化JSON
  const formatJson = (jsonStr: string) => {
    try {
      const obj = typeof jsonStr === 'string' ? JSON.parse(jsonStr) : jsonStr
      return JSON.stringify(obj, null, 2)
    } catch (error) {
      return jsonStr
    }
  }

  // 查看详情
  const handleDetail = (row: any) => {
    currentReview.value = row
    detailVisible.value = true
  }

  // 审核
  const handleApprove = (row: any, status: number) => {
    currentReview.value = row
    approveStatus.value = status
    approveForm.remark = ''
    approveVisible.value = true
  }

  // 确认审核
  const confirmApprove = async () => {
    submitting.value = true
    try {
      await request({
        url: '/api/crm/customer/reviewApprove',
        method: 'post',
        data: {
          id: currentReview.value.id,
          status: approveStatus.value,
          remark: approveForm.remark,
        },
      })

      ElMessage.success(approveStatus.value === 2 ? '审核通过' : '审核驳回')
      approveVisible.value = false
      getReviewList()
    } catch (error) {
      console.error('审核失败:', error)
    } finally {
      submitting.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.current = 1
    getReviewList()
  }

  // 重置
  const handleReset = () => {
    filterForm.status = ''
    pagination.current = 1
    getReviewList()
  }

  // 分页大小改变
  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.current = 1
    getReviewList()
  }

  // 当前页改变
  const handleCurrentChange = (current: number) => {
    pagination.current = current
    getReviewList()
  }

  onMounted(() => {
    getReviewList()
  })
</script>

<style scoped>
  .customer-review-list {
    padding: 20px;
  }

  .header {
    margin-bottom: 20px;
  }

  .filter {
    background: #f5f7fa;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
  }

  .pagination {
    margin-top: 20px;
    text-align: right;
  }

  .data-compare {
    margin-top: 20px;
  }

  .compare-card {
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .compare-card h5 {
    margin: 0 0 10px 0;
    color: #606266;
  }

  .compare-card pre {
    margin: 0;
    padding: 10px;
    background: #fff;
    border-radius: 4px;
    overflow-x: auto;
    font-size: 12px;
  }
</style>
